<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiPromptTemplatesApi } from '#/api/ai/prompt/promptTemplates';
import type { AiPromptVariablesApi } from '#/api/ai/prompt/promptVariables';

import { nextTick, ref, watch } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart } from '@vben/utils';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { exportPromptVariables } from '#/api/ai/prompt/promptVariables';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from './data';
import Detail from './modules/detail.vue';
import Form from './modules/form.vue';

const props = defineProps<{
  formData: AiPromptTemplatesApi.PromptTemplates;
}>();

const tableList = ref(props.formData.variablesList || []);
const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

const [DetailModal, detailModalApi] = useVbenModal({
  connectedComponent: Detail,
  destroyOnClose: true,
});

/** 切换树形展开/收缩状态 */
const isExpanded = ref(true);
function handleExpand() {
  isExpanded.value = !isExpanded.value;
  gridApi.grid.setAllTreeExpand(isExpanded.value);
}

/** 刷新表格 */
async function handleRefresh(newRow: AiPromptVariablesApi.PromptVariables) {
  if (newRow) {
    // 判断id是否存在
    const currentTableData = gridApi.grid?.getTableData().tableData || [];

    if (currentTableData.length > 0) {
      const index = currentTableData.findIndex((item) => item.id === newRow.id);
      if (index === -1) {
        currentTableData.push(newRow);
      } else {
        currentTableData[index] = newRow;
      }

      // 根据sort排序
      currentTableData.sort((a, b) => {
        if (a.sort < b.sort) {
          return -1;
        }
        if (a.sort > b.sort) {
          return 1;
        }
        return 0;
      });
    } else {
      currentTableData.push(newRow);
    }
    // 更新表格数据
    await gridApi.setGridOptions({ data: currentTableData });
    tableList.value = currentTableData;
  }
}

/** 创建提示词变量 */
function handleCreate() {
  const tableData = gridApi.grid?.getTableData().tableData || [];
  formModalApi
    .setData({ parentId: 0, promptId: props.formData.id, tableData })
    .open();
}

/** 编辑提示词变量 */
function handleEdit(row: AiPromptVariablesApi.PromptVariables) {
  const tableData = gridApi.grid?.getTableData().tableData || [];
  row.tableData = tableData;
  formModalApi.setData(row).open();
}

/** 查看提示词变量 */
function handleDetail(row: AiPromptVariablesApi.PromptVariables) {
  const tableData = gridApi.grid?.getTableData().tableData || [];
  row.tableData = tableData;
  detailModalApi.setData(row).open();
}

/** 新增下级提示词变量 */
function handleAppend(row: AiPromptVariablesApi.PromptVariables) {
  formModalApi
    .setData({ parentId: row.id, promptId: props.formData.id })
    .open();
}

/** 删除提示词变量 */
async function handleDelete(row: AiPromptVariablesApi.PromptVariables) {
  await gridApi.grid?.remove(row);
}
/** 导出表格 */
async function handleExport() {
  const data = await exportPromptVariables(await gridApi.formApi.getValues());
  downloadFileFromBlobPart({ fileName: '提示词变量.xls', source: data });
}
watch(
  () => props.formData.variablesList,
  (v) => {
    nextTick(() => {
      gridApi.setGridOptions({ data: v });
      tableList.value = v;
    });
  },
  { immediate: true },
);
defineExpose({
  getValues: () => {
    return tableList.value;
  },
});
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    id: 'PromptVariables-grid',
    columns: useGridColumns(),
    height: 'auto',
    treeConfig: {
      parentField: 'parentId',
      rowField: 'id',
      transform: true,
      expandAll: true,
      reserve: true,
    },
    pagerConfig: {
      enabled: false,
    },
    data: props.formData?.variablesList || [],
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<AiPromptVariablesApi.PromptVariables>,
  gridEvents: {},
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="handleRefresh" />
    <DetailModal />
    <Grid table-title="提示词变量列表">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: isExpanded ? '收缩' : '展开',
              type: 'primary',
              onClick: handleExpand,
            },
            {
              label: $t('ui.actionTitle.create', ['提示词变量']),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['ai:prompt-templates:create'],
              onClick: handleCreate,
            },
            {
              label: $t('ui.actionTitle.export'),
              type: 'primary',
              icon: ACTION_ICON.DOWNLOAD,
              auth: ['ai:prompt-templates:export'],
              onClick: handleExport,
            },
          ]"
        />
      </template>

      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: '新增下级',
              type: 'link',
              icon: ACTION_ICON.ADD,
              auth: ['ai:prompt-templates:create'],
              onClick: handleAppend.bind(null, row),
              ifShow:
                row.javaType === 'Object' ||
                (row.javaType === 'Array' &&
                  row.metadata?.arrayJavaType === 'Object'),
            },
            {
              label: '查看',
              type: 'link',
              icon: ACTION_ICON.VIEW,
              auth: ['ai:prompt-templates:query'],
              onClick: handleDetail.bind(null, row),
            },
            {
              label: $t('common.edit'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              auth: ['ai:prompt-templates:update'],
              onClick: handleEdit.bind(null, row),
            },
            {
              label: $t('common.delete'),
              type: 'link',
              danger: true,
              icon: ACTION_ICON.DELETE,
              auth: ['ai:prompt-templates:delete'],
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [row.id]),
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
